import axios from "axios";


const service = axios.create({
    baseURL: '/api',
    timeout: 30000 // 设置请求超时时间
})
// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem("token");
        if (token) {
            config.headers.Authorization = token;
        }
        return config
    }, (error) => {
        // 发送失败
        console.log(error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(response => {
        // dataAxios 是 axios 返回数据中的 data
        // loadingInstance.close();
        let res = response.data;

        if (res.code === 1) {
            return Promise.resolve(res.data);
        } else if (res.code === 401) {
            localStorage.clear()
            location.reload();
            console.log('token失效');
        } else {
            return Promise.reject(res.message);
        }
    },
    (error) => {
        if (error.response.data.code === 401) {
            localStorage.clear();
            location.reload();
            console.log('token失效');
        }
        return Promise.reject(error)
    }
)

export default service
